home *** CD-ROM | disk | FTP | other *** search
- ===========================================================================
- BBS: The Abacus * HST/DS * Potterville MI
- Date: 06-06-93 (09:15) Number: 57
- From: JERRY COFFIN Refer#: 142
- To: ROLLIN WHITE Recvd: NO
- Subj: Parsing a Text file Conf: (36) C Language
- ---------------------------------------------------------------------------
- On (03 Jun 93) Rollin White wrote to All...
-
- RW> Does anyone have code(or even a reccommended approach) fo
- RW> reading in a text file that will serve as a program's configuration
- RW> file? Specifically, keywords like:
- RW>
- RW> USER=John Doe
-
- #include <stdio.h>
- #include <string.h>
-
- /* Public Domain, by Jerry Coffin, tested with MSC 7.0 */
-
- char *get_config(char *name, FILE *file) {
-
- char buffer[200];
- char a_name[100];
- static char value[100];
- /* These lengths are arbitrarily selected, but should
- * be sufficient for most purposes.
- */
- size_t i,len;
-
- rewind(file);
- while (!feof(file)) {
- fscanf(file," %200[^\n]",buffer);
- if (';' == buffer[0] )
- continue;
- /* If the line starts with a semicolon, consider it a comment.
- * ( ignore it )
- */
- sscanf(buffer," %99[^ =] = %99[^\n]",a_name,value);
-
- /* This simply looks for some characters ending with either
- * whitespace or an equal sign, followed by an equal sign, then
- * some more characters. Any whitespace at the beginning of the
- * line or on either side of the equal sign will be ignored.
- */
-
- len = strlen(a_name);
- for (i=0;i<len;i++)
- if ('_' == a_name[i] )
- memmove(a_name+i,a_name+i+1,len-i);
- /* This strips underscore characters out of the name, so if any
- * are present, they will be ignored.
- */
-
- if (!stricmp(a_name,name))
- /* stricmp is non-standard, but most compilers include it. It
- * simply compares the two strings ignoring case.
- */
- break;
- else value[0] = '\0';
- /* Otherwise, make the string empty in case it's the last in the
- * file and there were no matches.
- */
- }
- return value;
- }
-
- #ifdef TEST
-
- int main(void) {
-
- FILE *config;
- char *name;
-
- if (NULL == (config =fopen("test.cfg","r" )))
- fprintf(stderr,"\nUnable to open configuration file");
-
- name = get_config("name",config);
- if (name[0])
- printf("my name is %s", get_config("name",config));
- else
- printf("I'm in bad shape - I can't even find my own name");
- fclose(config);
- return 0;
- }
- #endif
-
- ; test.cfg
- name=Jerry Coffin
- Later,
- Jerry.
-
- --- PPoint 1.60 "The Universe is a figment of its own imagination."
- * Origin: Point Pointedly Pointless (1:128/77.3)
- SEEN-BY: 1/211 11/2 4 13/13 101/1 108/89 109/25 110/69 114/5 123/19 124/1
- SEEN-BY: 153/752 154/40 77 157/110 159/100 125 430 575 950 203/23 209/209
- SEEN-BY: 261/1023 280/1 390/1 396/1 5 15 2270/1 2440/5 3603/20
-